#!/bin/bash
# Symlink-Fixer
# (called from Tar-gz-Package-Builder)


LINKS=`find ./ -name "*.svg" -type l`
for file in $LINKS
do

	#put the destination into $link
	LINE=`file $file` #receive an error saying that a file is a broken link of `../folder/destination.svg'
	BEGIN="\`";
	POS=`expr index "$LINE" $BEGIN`; #pos is the position of `
	POS=`expr $POS + 1`; 
	LENGTH=${#LINE}; # this is the lenght of the error message
	LENGTH=`expr $LENGTH - $POS`; #this is the length of ../folder/destination.svg
	LINK=`expr substr "$LINE" $POS $LENGTH`; #link has now the destination link

	#remove the old symlink
	rm $file;

	#change the destination format from .svg to .png
	LENGTH=${#LINK}; #this is the length of ../folder/destination.svg
	LENGTH=`expr $LENGTH - 4`;
	LINK=`expr substr "$LINK" 1 $LENGTH`; #link has now ../folder/destination
	LINK=$LINK".png"; #link has now the png extension ../folder/destination.png or ./destination.png

	#change the old symlink name from .svg to .png
	BEGIN="/";
	POS=`expr index "$file" $BEGIN`; #position of /name.svg
	POS=`expr $POS + 1`; #position of name.svg
	LENGTH=${#file}; #this is the length of ./name.svg
	file=`expr substr "$file" $POS $LENGTH`; #file now has name.svg
	LENGTH=${#file}; #this is the length of name.svg
	LENGTH=`expr $LENGTH - 4`; #this is the length of name
	file=`expr substr "$file" 1 $LENGTH`;
	file=$file".png"; #file has the name that the new symlink should have name.png

	#test if the destination is out of the directory or not
	TEST=`expr match "$LINK" '\(../\)'`;
	if [ "$TEST" = "" ]; then 

		#if the link has ./destination.png we remove ./
		BEGIN="/"; #link has ./destination.png
		POS=`expr index "$file" $BEGIN`; #position of /destination.png
		POS=`expr $POS + 1`; #position of destination.png
		LENGTH=${#file}; #this is the length of ./destination.png
		file=`expr substr "$file" $POS $LENGTH`; #file now has destination.png

		#and link it (renaming it at the same time)
		ln -s $LINK $file
	else
		#we link it from an outer directory
		ln -s $LINK; #create the symlink

		#obtain the name of the link we have just created (removin ../folder/)
		LENGTH=${#LINK}; #length of ../folder/destination.png
		POS=`expr index "$LINK" $BEGIN`; #position of /folder/destination.png
		POS=`expr $POS + 1`; #position of folder/destination.png
		LINK=`expr substr "$LINK" $POS $LENGTH`; #folder/destination.png
		LENGTH=${#LINK}; #length of folder/destination.png
		POS=`expr index "$LINK" $BEGIN`; #position of /destination.png
		POS=`expr $POS + 1`; #position of destination.png
		LINK=`expr substr "$LINK" $POS $LENGTH`; #link now has the name of the new symlink
		#rename the link created to its right name
		if [ "$LINK" != "$file" ]; then #only if they are not the same
			#this is for those files that do not have the same name in the two directory
			#for example file.png links to ../folder/any.png (not to a same name file ../folder/file.png)
			mv $LINK $file; #rename the file
		fi
	fi
done 
exit 0
